package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.request.SalesPlanSyncSapDetailDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.SalesPlanSyncSapRequestDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.SalesPlanSyncDetailSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.SalesPlanSyncSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.RequestUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.dto.CallbackRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.dto.PlanAdjustSyncCRMRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.dto.PlanAdjustSyncSAPRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.dto.PlanSyncCRMRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.dto.PlanSyncSAPRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapifsalesplan.service.MnSapIfSalesPlanService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SalesPlanSyncCrmDetail;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SalesPlanSyncCrmRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SalesPlanSyncSapDetail;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SalesPlanSyncSapRequest;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf006Request;
import com.epoch.app.otsapplicationadaptersdk.service.ApiAdapterService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: 中台请求SAP、CRM同步月度计划数据    sap048,049
 * @date 2024/4/7 16:11
 */
@Component
public class MnSapIfSalesPlanServiceImpl implements MnSapIfSalesPlanService {
    private static final Logger log = LoggerFactory.getLogger(MnSapIfSalesPlanServiceImpl.class);

    @Resource
    private ApiAdapterService apiAdapterService;

    @Autowired
    private HttpUtils httpUtils;

    private String test(){
        String aaa = "";
        return aaa;
    }


    @Override
    @ProcessInvoker(remark = "planSyncSAP", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object planSyncSAP(PlanSyncSAPRequest planSyncSAPRequest) {
        SalesPlanSyncSDO planSyncSDO = JSON.parseObject(planSyncSAPRequest.getMessage(), SalesPlanSyncSDO.class);
        if (planSyncSDO == null || CollectionUtils.isEmpty(planSyncSDO.getDetails())){
            log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_data_is_null");
            return Result.success(true);
        }

        SalesPlanSyncSapRequestDTO req = new SalesPlanSyncSapRequestDTO();
        req.setMessageHeader(RequestUtils.generateMessageHeaderCopy("SI_ZT_MonthPlan_Asyn_OUT","YWZT", "ECC"));
        req.setZYEARM(planSyncSDO.getPlanTime());
        req.setDIVISION(planSyncSDO.getScItemGroup());
        req.setVKORG(planSyncSDO.getSalesOrganizationCode());
//        req.setCREATED_ON();
//        req.setCREATED_IN();
//        req.setCREATED_BY();
//        req.setCHANGED_ON();
//        req.setCHANGED_IN();
//        req.setCHANGED_BY();

        List<SalesPlanSyncSapDetailDTO> detailList = planSyncSDO.getDetails().stream().map(x->{
            SalesPlanSyncSapDetailDTO detail = new SalesPlanSyncSapDetailDTO();
            detail.setPARTNER(x.getCustomerCode());
            detail.setPRODUCT(x.getScItemCode());
            detail.setZQTY_U3(x.getMonthFirstReturnCount().toString());
            detail.setZQTY_M3(x.getMonthMiddleReturnCount().toString());
            detail.setZQTY_D3(x.getMonthLastReturnCount().toString());
            detail.setZQTY_PLAN12(x.getM1RollingPlanCount().toString());
            detail.setZQTY_PLAN22(x.getM2RollingPlanCount().toString());
            detail.setZQTY_PLAN32(x.getM3RollingPlanCount().toString());
            detail.setZPRICE(x.getOutboundPrice());
            detail.setZPR_ZKL(x.getDiscountRate());
            return detail;
        }).collect(Collectors.toList());

        req.setItems(detailList);

//        String url = OtsApplicationAdapterSdkConstants.urlPrefix() + "/api/ots_application_adapter_sdk/rest_sap_sales_plan_sync";
//        Map<String, String> epochHeader = HttpTokenUtil.generateHttpHeader();
//        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_req:url={},header={}", url,JSONObject.toJSONString(epochHeader));
//        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_req_body={}", JSONObject.toJSONString(req));
//        ResponseEntity<com.alibaba.lattice2.epoch.sdk.model.Result> resEntity = httpUtils.post(url, epochHeader, req, com.alibaba.lattice2.epoch.sdk.model.Result.class);
//        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_resEntity:{}", JSONObject.toJSONString(resEntity));


        String sapUrl = "http://"+OtsApplicationAdapterSdkConstants.rest_sap_ip_and_port()+"/RESTAdapter/ZT/ECC/SI_ZT_MonthPlan_Asyn_OUT";
        Map<String, String> sapHeader = new HashMap<>();
        sapHeader.put("Authorization", OtsApplicationAdapterSdkConstants.rest_sap_authorization());
        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_req_1:url={},Authorization={}", sapUrl,OtsApplicationAdapterSdkConstants.rest_sap_authorization());
        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_req_body_1,total={},req={}", req.getItems().size(), JSONObject.toJSONString(req));
        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_req_body_header_1:,messageHeader={}", JSONObject.toJSONString(req.getMessageHeader()));
        ResponseEntity<com.alibaba.lattice2.epoch.sdk.model.Result> resultEntity = httpUtils.post(sapUrl, sapHeader, req, com.alibaba.lattice2.epoch.sdk.model.Result.class);
        log.info("MnSapIfSalesPlanServiceImpl_planSyncSAP_resEntity_1:{}", JSONObject.toJSONString(resultEntity));

//        apiAdapterService.reqSapSalesPlanSync(req);
        return Result.success(true);
    }

    @Override
    @ProcessInvoker(remark = "planAdjustSyncSAP", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object planAdjustSyncSAP(PlanAdjustSyncSAPRequest planAdjustSyncSAPRequest) {
        SalesPlanSyncSDO planSyncSDO = JSON.parseObject(planAdjustSyncSAPRequest.getMessage(), SalesPlanSyncSDO.class);
        if (planSyncSDO == null || CollectionUtils.isEmpty(planSyncSDO.getDetails())){
            log.info("MnSapIfSalesPlanServiceImpl_planAdjustSyncSAP_data_is_null");
            return Result.success(true);
        }

        SalesPlanSyncSapRequest req = new SalesPlanSyncSapRequest();
        req.setMessageHeader(RequestUtils.generateMessageHeader("SI_ZT_FiveDayAdjustPlan_Asyn_OUT","YWZT", "ECC"));
        req.setZYEARM(planSyncSDO.getPlanTime());
        req.setDIVISION(planSyncSDO.getScItemGroup());
        req.setVKORG(planSyncSDO.getSalesOrganizationCode());
        req.setDISTR_CHAN(planSyncSDO.getChannelCode());
//        req.setCREATED_ON();
//        req.setCREATED_IN();
//        req.setCREATED_BY();
//        req.setCHANGED_ON();
//        req.setCHANGED_IN();
//        req.setCHANGED_BY();

        List<SalesPlanSyncSapDetail> detailList = new ArrayList<>();
        for (SalesPlanSyncDetailSDO sdo:planSyncSDO.getDetails()) {
            SalesPlanSyncSapDetail detail = new SalesPlanSyncSapDetail();
            detail.setPARTNER(sdo.getCustomerCode());
            detail.setPRODUCT(sdo.getScItemCode());
            detail.setUNIT(sdo.getScItemUnit());
            detail.setZPRICE(sdo.getOutboundPrice());
            detail.setZPR_ZKL(sdo.getDiscountRate());
            if (sdo.getMonthFirstAdjustReturnCount() != 0) {
                SalesPlanSyncSapDetail bean = new SalesPlanSyncSapDetail();
                BeanUtils.copyProperties(detail,bean);
                bean.setZIP_X("S");
                bean.setZIP_TBZS(sdo.getMonthFirstAdjustReturnCount().toString());
                detailList.add(bean);
            }
            if (sdo.getMonthMiddleAdjustReturnCount() != 0) {
                SalesPlanSyncSapDetail bean = new SalesPlanSyncSapDetail();
                BeanUtils.copyProperties(detail,bean);
                bean.setZIP_X("Z");
                bean.setZIP_TBZS(sdo.getMonthMiddleAdjustReturnCount().toString());
                detailList.add(bean);
            }
            if (sdo.getMonthLastAdjustReturnCount() != 0) {
                SalesPlanSyncSapDetail bean = new SalesPlanSyncSapDetail();
                BeanUtils.copyProperties(detail,bean);
                bean.setZIP_X("X");
                bean.setZIP_TBZS(sdo.getMonthLastAdjustReturnCount().toString());
                detailList.add(bean);
            }
        }
        req.setItems(detailList);

        return apiAdapterService.reqSapSalesPlanAdjustSync(req);
    }


    @Override
    @ProcessInvoker(remark = "planSyncCRM", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object planSyncCRM(PlanSyncCRMRequest planSyncCRMRequest) {
        SalesPlanSyncSDO planSyncSDO = JSON.parseObject(planSyncCRMRequest.getMessage(), SalesPlanSyncSDO.class);
        if (planSyncSDO == null || CollectionUtils.isEmpty(planSyncSDO.getDetails())){
            log.info("MnSapIfSalesPlanServiceImpl_planSyncCRM_data_is_null");
            return Result.success(true);
        }

        SalesPlanSyncCrmRequest req = new SalesPlanSyncCrmRequest();
        req.setMessageHeader(RequestUtils.generateMessageHeader("SI_ZT_CrmMonthPlan_Syn_OUT","YWZT", "ECC"));

        List<SalesPlanSyncCrmDetail> detailList = planSyncSDO.getDetails().stream().map(x->{
            SalesPlanSyncCrmDetail detail = new SalesPlanSyncCrmDetail();
            detail.setZYEARM(planSyncSDO.getPlanTime());
            detail.setR4_ORG(planSyncSDO.getSalesOrganizationCode());
            detail.setDIVISION(planSyncSDO.getScItemGroup());
            detail.setPARTNER(x.getCustomerCode());
            detail.setPRODUCT(x.getScItemCode());
            detail.setZQTY_U1(x.getMonthFirstCount().toString());
            detail.setZQTY_M1(x.getMonthMiddleCount().toString());
            detail.setZQTY_D1(x.getMonthLastCount().toString());
            detail.setZQTY_U3(x.getMonthFirstReturnCount().toString());
            detail.setZQTY_M3(x.getMonthMiddleReturnCount().toString());
            detail.setZQTY_D3(x.getMonthLastReturnCount().toString());
            detail.setZQTY_U5(x.getMonthFirstAdjustTotalCount().toString());
            detail.setZQTY_M5(x.getMonthMiddleAdjustTotalCount().toString());
            detail.setZQTY_D5(x.getMonthLastAdjustTotalCount().toString());
            detail.setZQTY_PLAN12(x.getM1RollingPlanCount().toString());
            detail.setZQTY_PLAN22(x.getM2RollingPlanCount().toString());
            detail.setZQTY_PLAN32(x.getM3RollingPlanCount().toString());
            detail.setZPRICE(x.getOutboundPrice());
            detail.setZPR_ZKL(x.getDiscountRate());
            return detail;
        }).collect(Collectors.toList());
        req.setItems(detailList);

        return apiAdapterService.reqCrmSalesPlanSync(req);
    }


    @Override
    @ProcessInvoker(remark = "planSyncCRM", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object planAdjustSyncCRM(PlanAdjustSyncCRMRequest planAdjustSyncCRMRequest) {
        SalesPlanSyncSDO planSyncSDO = JSON.parseObject(planAdjustSyncCRMRequest.getMessage(), SalesPlanSyncSDO.class);
        if (planSyncSDO == null || CollectionUtils.isEmpty(planSyncSDO.getDetails())){
            log.info("MnSapIfSalesPlanServiceImpl_planAdjustSyncCRM_data_is_null");
            return Result.success(true);
        }

        SalesPlanSyncCrmRequest req = new SalesPlanSyncCrmRequest();
        req.setMessageHeader(RequestUtils.generateMessageHeader("SI_ZT_CrmMonthPlan_Syn_OUT","YWZT", "ECC"));

        List<SalesPlanSyncCrmDetail> detailList = planSyncSDO.getDetails().stream().map(x->{
            SalesPlanSyncCrmDetail detail = new SalesPlanSyncCrmDetail();
            detail.setZYEARM(planSyncSDO.getPlanTime());
            detail.setR4_ORG(planSyncSDO.getSalesOrganizationCode());
            detail.setDIVISION(planSyncSDO.getScItemGroup());
            detail.setPARTNER(x.getCustomerCode());
            detail.setPRODUCT(x.getScItemCode());
            detail.setZQTY_U1(x.getMonthFirstCount().toString());
            detail.setZQTY_M1(x.getMonthMiddleCount().toString());
            detail.setZQTY_D1(x.getMonthLastCount().toString());
            detail.setZQTY_U3(x.getMonthFirstReturnCount().toString());
            detail.setZQTY_M3(x.getMonthMiddleReturnCount().toString());
            detail.setZQTY_D3(x.getMonthLastReturnCount().toString());
            detail.setZQTY_U5(x.getMonthFirstAdjustTotalCount().toString());
            detail.setZQTY_M5(x.getMonthMiddleAdjustTotalCount().toString());
            detail.setZQTY_D5(x.getMonthLastAdjustTotalCount().toString());
            detail.setZQTY_PLAN12(x.getM1RollingPlanCount().toString());
            detail.setZQTY_PLAN22(x.getM2RollingPlanCount().toString());
            detail.setZQTY_PLAN32(x.getM3RollingPlanCount().toString());
            detail.setZPRICE(x.getOutboundPrice());
            detail.setZPR_ZKL(x.getDiscountRate());
            return detail;
        }).collect(Collectors.toList());
        req.setItems(detailList);

        return apiAdapterService.reqCrmSalesPlanSync(req);
    }


    @Override
    @ProcessInvoker(remark = "planSyncCallback", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object callback(CallbackRequest callbackRequest) {
        MnSapIf006Request mnSapIf006Request = JSON.parseObject(callbackRequest.getMessage(), MnSapIf006Request.class);

        if (mnSapIf006Request == null
                || CollectionUtils.isEmpty(mnSapIf006Request.getData())
                || !"true".equals(mnSapIf006Request.getData().get(0).getSuccess())){

            log.error("MnSapIfSalesPlanServiceImpl_planSyncSapCallback_fail,message={}",callbackRequest.getMessage());
            return Result.failure("-1",callbackRequest.getMessage());
        }
        return Result.success(true);
    }

}
